﻿using System;
using System.IO;

namespace USU.MetricsMonitor.Common
{
	/// <summary>
	/// This class is caching wrapper of readable stream, it caches everything it reads
	/// to the cache stream. It also takes care of closing and disposing read and cace streams
	/// where appropriate
	/// </summary>
	public class CachingStream : Stream
	{
		private readonly Stream cacheStream;
		private readonly Stream readStream;

		public CachingStream(Stream readStream, Stream cacheStream)
		{
			if (!readStream.CanRead)
				throw new ArgumentException("Not readable stream passed as first arg");
			if (!cacheStream.CanWrite)
				throw new ArgumentException("Not writable stream passed as second arg");

			this.cacheStream = cacheStream;
			this.readStream = readStream;
		}

		public override void Close()
		{
			cacheStream.Close();
			readStream.Close();
			base.Close();
		}

		protected override void Dispose(bool disposing)
		{
			cacheStream.Dispose();
			readStream.Dispose();
			base.Dispose(disposing);
		}

		public override void Flush() { cacheStream.Flush(); }

		public override long Seek(long offset, SeekOrigin origin) { return readStream.Seek(offset, origin); }

		public override void SetLength(long value) { readStream.SetLength(value); }

		public override int Read(byte[] buffer, int offset, int count)
		{
			var ret = readStream.Read(buffer, offset, count);
			cacheStream.Write(buffer, offset, ret);
			return ret;
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			readStream.Write(buffer, offset, count);
		}

		public override bool CanRead { get { return readStream.CanRead; } }

		public override bool CanSeek { get { return readStream.CanSeek; } }

		public override bool CanWrite { get { return readStream.CanWrite; } }

		public override long Length { get { return readStream.Length; } }

		public override long Position
		{
			get { return readStream.Position; }
			set { readStream.Position = value; }
		}
	}
}
